//
//  VGCarouselView.swift
//  vgbox
//
//  Created by 宋海胜 on 2019/7/2.
//  Copyright © 2019 Swift Xcode. All rights reserved.
//  通用轮播  只要将需要轮播的 cell样式，model类型 在init控件时传进来，通过setDataSource方法给轮播赋值即可

import UIKit

// 轮播cell需要实现协议中的cell赋值方法
protocol VGCarouselViewCellProtocol {
    func configCell(_ model: VGCarouserlModel)
}


///  通用轮播
class VGCarouselView<M: VGCarouserlModel, C: UICollectionViewCell>: UIView, UICollectionViewDelegate, UICollectionViewDataSource where C: VGCarouselViewCellProtocol {

    public var didSelectCellClosure: ((Int) -> Void)?
    
    public var scrollToCellClosure: ((Int) -> Void)?
    
    fileprivate var dataSource: [M] = []
    
    fileprivate var collectionView: UICollectionView!
    
    fileprivate var timer: Timer!
    
    fileprivate var currentIndex: Int = 1 {
        didSet {
            scrollToCellClosure?(currentIndex)
        }
    }
    
    init(frame: CGRect, customCollecionView: UICollectionView?) {
        super.init(frame: frame)
        
        setupCollectionView(frame, customCollecionView)
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    @objc func timerAction() {
        
        self.currentIndex += 1
        if self.dataSource.count > self.currentIndex {
            self.collectionView.scrollToItem(at: IndexPath(item: self.currentIndex, section: 0), at: UICollectionView.ScrollPosition.init(rawValue: 0), animated: true)
        }
        
        // 动画结束后立即判断
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            self.judgeIsFirstOne()
        }
    }
    
    public func setDataSource(_ dataSource: [M], autoRunEnabled: Bool = true) {
        
        self.stopTimer()
        self.dataSource = dataSource
        self.handleDataSource()
        self.collectionView.reloadData()
        if dataSource.count >= 2 {
            currentIndex = 1
            collectionView.scrollToItem(at: IndexPath(item: currentIndex, section: 0), at: UICollectionView.ScrollPosition.init(rawValue: 0), animated: false)
            if autoRunEnabled {
                self.startTimer()
            }
        }
    }
    
    // 判断是否是第一个 1
    fileprivate func judgeIsFirstOne() {
        if currentIndex >= dataSource.count - 1 {
            currentIndex = 1
            collectionView.scrollToItem(at: IndexPath(item: currentIndex, section: 0), at: UICollectionView.ScrollPosition.init(rawValue: 0), animated: false)
        }
    }
    
    // 判断是否是最后一个 3
    fileprivate func judgeIsLastOne() {
        if currentIndex == 0 {
            currentIndex = dataSource.count - 2
            collectionView.scrollToItem(at: IndexPath(item: currentIndex, section: 0), at: UICollectionView.ScrollPosition.init(rawValue: 0), animated: false)
        }
    }
    
    ///滑动滚动到第几个cell
    public func selectIndex(_ currentIndex : Int){
        self.currentIndex = currentIndex
        collectionView.scrollToItem(at: IndexPath(item: currentIndex, section: 0), at: UICollectionView.ScrollPosition.init(rawValue: 0), animated: false)
    }
    
    fileprivate func handleDataSource() {
        
        // 数组由 1 2 3 变成 3 1 2 3 1
        if dataSource.count >= 2 {
            let fir: M = dataSource.last!
            let last: M = dataSource.first!
            
            fir.currentIndex = dataSource.count
            last.currentIndex = 1
            for (i, value) in dataSource.enumerated() {
                value.currentIndex = i + 1
            }
            
            dataSource.append(last)
            dataSource.insert(fir, at: 0)
        } else if dataSource.count == 1 {
            dataSource.first?.currentIndex = 1
        }
    }
    
    fileprivate func startTimer() {
        
        if timer == nil {        
            timer = Timer.scheduledTimer(timeInterval: 4, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
            RunLoop.current.add(timer, forMode: RunLoop.Mode.common)
            timer.fire()
        }
    }
    
    fileprivate func stopTimer() {
        if self.timer != nil && self.timer.isValid {
            self.timer.invalidate()
            self.timer = nil
        }
    }
    
    // 自定义collectionview
    fileprivate func setupCollectionView(_ frame: CGRect, _ customCollecionView: UICollectionView?) {
        
        if customCollecionView == nil {
            
            let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
            layout.itemSize = frame.size
            layout.minimumLineSpacing = 0
            layout.scrollDirection = .horizontal
            collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height), collectionViewLayout: layout)
            collectionView.backgroundColor = .white
            collectionView.showsHorizontalScrollIndicator = false
            
        } else {
            self.collectionView = customCollecionView
        }
        
        
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(C.self, forCellWithReuseIdentifier: NSStringFromClass(C.self))
        self.addSubview(self.collectionView)
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: C? = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(C.self), for: indexPath) as? C
        if let d = dataSource.objectAtIndex(index: indexPath.row) {
            cell?.configCell(d)
        }
        return cell!
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.row == 0 {
            if dataSource.count == 1 {
                didSelectCellClosure?(0)
            } else {            
                didSelectCellClosure?(dataSource.count - 3)
            }
        } else if indexPath.row == dataSource.count - 1 {
            didSelectCellClosure?(0)
        } else {
            didSelectCellClosure?(indexPath.row - 1)
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        if timer != nil {
            // 2s后启动
            timer.fireDate = Date(timeIntervalSinceNow: 1)
        }
        
        // 该方法不准
//        if let cell: C = collectionView.visibleCells.first as? C {
//            currentIndex = (collectionView.indexPath(for: cell)?.row)!
//        }
//        let index: Int = Int(scrollView.contentOffset.x / self.frame.size.width)
//        if (scrollView.contentOffset.x.truncatingRemainder(dividingBy: self.frame.size.width)) != 0 {
//            index += 1
//        }
        
        judgeIsFirstOne()
        judgeIsLastOne()
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offsetX = scrollView.contentOffset.x
        let page = Int(offsetX / self.frame.size.width + 0.5)
        currentIndex = page
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        if timer != nil {
            // 拖拽时暂停
            timer.fireDate = Date.distantFuture
        }
    }
}


/// 轮播基础model
class VGCarouserlModel: NSObject {
    // 获取当前cell的index
    var currentIndex: Int = 0
}
